const pool = require('../models/db');

const tagController = {
    // 获取所有标签
    getAllTags: async (req, res) => {
        try {
            const [tags] = await pool.query(`
                SELECT t.*, 
                       COUNT(DISTINCT at.article_id) as article_count
                FROM tags t
                LEFT JOIN article_tags at ON t.id = at.tag_id
                GROUP BY t.id
                ORDER BY article_count DESC
            `);
            res.json(tags);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取单个标签
    getTagById: async (req, res) => {
        try {
            const [tags] = await pool.query(
                'SELECT * FROM tags WHERE id = ?',
                [req.params.id]
            );

            if (tags.length === 0) {
                return res.status(404).json({ message: '标签不存在' });
            }

            res.json(tags[0]);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取标签下的所有文章
    getTagArticles: async (req, res) => {
        try {
            const [articles] = await pool.query(`
                SELECT a.*, 
                       u.username as author_name,
                       c.name as category_name,
                       GROUP_CONCAT(t2.name) as tags
                FROM articles a
                JOIN article_tags at ON a.id = at.article_id
                LEFT JOIN users u ON a.author_id = u.id
                LEFT JOIN categories c ON a.category_id = c.id
                LEFT JOIN article_tags at2 ON a.id = at2.article_id
                LEFT JOIN tags t2 ON at2.tag_id = t2.id
                WHERE at.tag_id = ? AND a.status = 'published'
                GROUP BY a.id
                ORDER BY a.created_at DESC
            `, [req.params.id]);

            articles.forEach(article => {
                article.tags = article.tags ? article.tags.split(',') : [];
            });

            res.json(articles);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 创建标签
    createTag: async (req, res) => {
        try {
            const { name } = req.body;
            const [result] = await pool.query(
                'INSERT INTO tags (name) VALUES (?)',
                [name]
            );

            res.status(201).json({
                message: '标签创建成功',
                tagId: result.insertId
            });
        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                return res.status(400).json({ message: '标签名称已存在' });
            }
            res.status(500).json({ error: error.message });
        }
    },

    // 更新标签
    updateTag: async (req, res) => {
        try {
            const { name } = req.body;
            const [result] = await pool.query(
                'UPDATE tags SET name = ? WHERE id = ?',
                [name, req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '标签不存在' });
            }

            res.json({ message: '标签更新成功' });
        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                return res.status(400).json({ message: '标签名称已存在' });
            }
            res.status(500).json({ error: error.message });
        }
    },

    // 删除标签
    deleteTag: async (req, res) => {
        try {
            const [result] = await pool.query(
                'DELETE FROM tags WHERE id = ?',
                [req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '标签不存在' });
            }

            res.json({ message: '标签删除成功' });
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }
};

module.exports = tagController;